//=============================================================================
// System  : MatchKit
// File    : ObjectPattern.cs
// Author  : Fabio Bussu  (matchkit@fabiobussu.it)
// Updated : 04/16/2013
// Note    : Copyright 2013, Fabio Bussu, All rights reserved
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code.  It can also be found
// at the project website: http://matchkit.codeplex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version     Date     Who  Comments
// ============================================================================
// 1.0.0.0  04/16/2013   FB  First draft
//=============================================================================
using System;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using MatchKit.Patterns;

namespace MatchKit.ObjectMapping.Patterns
{
	/// <summary>
	/// Provides the logic to match a matchable class.
	/// </summary>
	/// <threadsafety static="true" instance="false" />
	/// <serialization binary="true" contract="true" />
	/// <conceptualLink target="0a06b2a9-5f58-409a-ba62-639cfd77bca7" />
	#if DC
	[DataContract]
	#endif
	#if SZ
	[Serializable]
	#endif
	public sealed class ObjectPattern : BasePattern
	{
		#if DC
		[DataMember]
		#endif
		private Type _type;
		#if DC
		[DataMember]
		#endif
		private object _instance;
		#if DC
		[DataMember]
		#endif
		private bool _isForArray;
		#if DC
		[DataMember]
		#endif
		private ConstructorInfo _ctor;

		private bool _endsWithEos = false;
		/// <summary>
		/// Gets or sets a value specifying whether to ensure that the end of string must be reached 
		/// after matched all matchable members.
		/// </summary>
		/// <serialization member="true" />
		#if DC
		[DataMember]
		#endif
		public bool EndsWithEos
		{
			get { return _endsWithEos; }
			set { _endsWithEos = value; }
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="T:MatchKit.ObjectPattern"/> class. 
		/// </summary>
		/// <param name="type">Type to match. A new instance is automatically created. This value cannot be null.</param>
		public ObjectPattern(Type type)
			: this(type, false)
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="T:MatchKit.ObjectPattern"/> class. 
		/// </summary>
		/// <param name="type">Type to match. A new instance is automatically created. This value cannot be null.</param>
		/// <param name="isArray">Value specifying whether the member is an array.</param>
		public ObjectPattern(Type type, bool isArray)
		{
			if (type == null)
				throw new ArgumentNullException("type", "type cannot be null");
			_type = type;
			_isForArray = isArray;
			_ctor = Utils.GetDefaultConstructor(_type);
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="T:MatchKit.ObjectPattern"/> class. 
		/// </summary>
		/// <param name="instance">Instance to use for the match. This value cannot be null.</param>
		public ObjectPattern(object instance)
			: this(instance, false)
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="T:MatchKit.ObjectPattern"/> class. 
		/// </summary>
		/// <param name="instance">Instance to use for the match. This value cannot be null.</param>
		/// <param name="isArray">Value specifying whether the member is an array.</param>
		public ObjectPattern(object instance, bool isArray)
		{
			if (instance == null)
				throw new ArgumentNullException("instance", "instance cannot be null");
			_instance = instance;
			_type = _instance.GetType();
			_isForArray = isArray;
		}

		/// <inheritdoc />
		protected override Match OnMatch(MatchContext context)
		{
			var mappingContext = (ObjectMappingContext)context;

			var classInfo = MatchableClassInfo.Get(_type);
			var instance = _instance ?? _ctor.Invoke(null);
			var mappingEvents = classInfo.HasMappingEvents ? (IMatchMappingEvents)instance : null;
			var repeatableMemberMatched = false;
			var isPNRreached = false;
			var suspendBlankIgnoringAfterMember = false;

			foreach (var member in classInfo.Members)
			{
				// se il membro e' un repeating-element e non devo fare match di un array, salto il membro
				if (member.IsSeparatorElement && !_isForArray)
					continue;

				var p = member.CreatePattern(instance);

				if (!suspendBlankIgnoringAfterMember)
					SkipNulls(mappingContext);

				var branch = context.Branch();
				var m = p.Match(branch);

				if (m.Success && mappingContext.MatchingBag != null)
					mappingContext.MatchingBag.Trace(instance, member.RawMember.Member, m);

				if (member.IsSeparatorElement)
					repeatableMemberMatched = m.Success;

				if (!m.Success)
				{
					// IsRepeatingElement dovrebbe gia' essere opzionale di default, ma per sicurezza..
					if (m.IsOptional || member.IsSeparatorElement)
					{
						// empty
					}
					else
					{
						// se ho raggiunto il punto di non ritorno, esco con l'errore
						if (isPNRreached)
							ThrowPointOfNoReturnReached(m);
						return m;
					}

					if (member.IsFinalIfNotfound)
						break;
				}
				else
				{
					suspendBlankIgnoringAfterMember = member.SuspendBlankIgnoringAfterMember;

					context.Commit(branch);
				}

				if (!isPNRreached)
					isPNRreached = p.IsPointOfNoReturn;

				object typedValue = m.Value;

				if (m.Success && !member.IsReadOnly)	// Success potrebbe essere false se opzionale
					#region setting value
				{
					if (member.IsArray)
					{
						try
						{
							typedValue = CastArray((Array)typedValue, member.Type, member);
						}
						catch (Exception ex)
						{
							throw new MatchKitMappingException(32
								, string.Format("Invalid array conversion to type [{0}] for member [{1}]"
								, member.Type, member.RawMember.FullName), ex);
						}
					}
					else if (member.IsTypeMatch)
						typedValue = m;
					else if (member.IsTypeIPattern)
						typedValue = m.Pattern;
					else if (member.IsString)
						typedValue = typedValue == null ? null : typedValue.ToString();
					else if (member.IsNumber)
						typedValue = ReflectionUtils.CastNumberTo(typedValue, member.Type);

					if (mappingEvents != null)
					{
						var matchMappingEventArgs = new MatchMappingArgs(member.RawMember.Member, m, typedValue);
						mappingEvents.OnMatchingMember(matchMappingEventArgs);

						if (!matchMappingEventArgs.Cancel)
						{
							typedValue = matchMappingEventArgs.Value;
						}
					}

					try
					{
						member.RawMember.SetValue(instance, typedValue);
					}
					catch (Exception ex)
					{
						throw new MatchKitMappingException(33
							, string.Format("Invalid value assignation from value [{0}] for member [{1}]"
							, typedValue== null ? "<NULL>" : typedValue.ToString(), member.RawMember.FullName), ex);
					}
				}
				#endregion
			}

			if (!suspendBlankIgnoringAfterMember)
				SkipNulls(mappingContext);

			#region Ends with EOS
			if (_endsWithEos)
			{
				var m = new EosPattern().Match(context);
				if (!m.Success)
				{
					// se ho raggiunto il punto di non ritorno, esco con l'errore
					if (isPNRreached)
						ThrowPointOfNoReturnReached(m);
					return m;
				}
			}
			#endregion

			if (mappingEvents != null)
				mappingEvents.OnMatchedInstance();

			return new ObjectMatchInfo(context, this, true)
			{
				Value = instance,
				RepeatableMemberMatched = repeatableMemberMatched,
				HasRepeatingElement = classInfo.SeparatorElement != null
			};
		}

		/// <inheritdoc />
		public override string HelpString
		{
			get
			{
				return "Matchable class <" + _type.Name + ">";
			}
		}

		private static Array CastArray(Array source, Type targetType, MatchableMemberInfo memberInfo)
		{
			if (source == null)
				return null;
			if (source.Length == 0)
				return null;

			var targetArrayType = targetType.MakeArrayType();
			var target = (Array)Activator.CreateInstance(targetArrayType, source.Length);

			for (int six = 0; six < source.Length; six++)
			{
				var v = source.GetValue(six);
				if (memberInfo.IsNumber)
					v = Convert.ChangeType(v, targetType, CultureInfo.InvariantCulture);
				target.SetValue(v, six);
			}

			return target;
		}

		private void SkipNulls(ObjectMappingContext context)
		{
			while (SkipBlanks(context) || SkipNullPattern(context)) ;
		}

		private bool SkipNullPattern(ObjectMappingContext context)
		{
			var anySkipped = false;
			var np = context.NullPattern;
			if (np != null)
			{
				var tracer = context.Tracer;
				int index = 0;
				if (tracer != null)
				{
					index = context.Index;
					IMatchTracerExtensions.Verbose(tracer, context, this, "Trying skipping blanks");
				}

				while (true)
				{
					var branch = context.Branch();
					var m = np.Match(branch);
					if (!m.Success)
						break;
					context.Commit(branch);
					anySkipped = true;
				}

				if (tracer != null)
				{
					var endat = context.Index;
					if (index == endat)
						IMatchTracerExtensions.Verbose(tracer, context, this, "No null pattern to skip");
					else
						IMatchTracerExtensions.Verbose(tracer, context, this, "Skipped \"{0}\"", context.TargetText.Substring(index, endat - index));
				}
			}
			return anySkipped;
		}

		private bool SkipBlanks(ObjectMappingContext context)
		{
			var ignore = context.IgnoreBlanks;
			var ignoreNL = (ignore & IgnoreBlank.NewLine) != 0;
			var ignoreWS = (ignore & IgnoreBlank.WhiteSpace) != 0;
			var anySkipped = false;
			if (ignore != IgnoreBlank.None)
			{
				int index = 0;
				var tracer = context.Tracer;
				if (tracer != null)
				{
					index = context.Index;
					IMatchTracerExtensions.Verbose(tracer, context, this, "Trying skipping blanks");
				}

				while (true)
				{
					var ch = context.Current;
					if (ch == '\r' || ch == '\n')
					{
						if (ignoreNL)
						{
							anySkipped = true;
							context.NextCharacter();
						}
						else
							break;
					}
					else if (char.IsWhiteSpace(ch))
					{
						if (ignoreWS)
						{
							anySkipped = true;
							context.NextCharacter();
						}
						else
							break;
					}
					else
						break;
				}

				if (tracer != null)
				{
					var endat = context.Index;
					if (index == endat)
						IMatchTracerExtensions.Verbose(tracer, context, this, "No blanks to skip");
					else
						IMatchTracerExtensions.Verbose(tracer, context, this, "Skipped \"{0}\"", context.TargetText.Substring(index, endat - index));
				}
			}
			return anySkipped;
		}
	}
}
